package com.cssl.service.impl;


import cn.hutool.core.util.StrUtil;
import com.cssl.domain.DtsGoods;
import com.cssl.domain.DtsGroupOnRules;
import com.cssl.mapper.GroupOnMapper;
import com.cssl.service.GroupOnService;
import com.cssl.util.InfoCode;
import com.cssl.util.ObjectMapperUtil;
import com.cssl.util.Result;
import com.cssl.util.StorageVariable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//@Service
//public class GroupOnServiceImpl implements GroupOnService {
//    @Autowired
//    private GroupOnMapper mapper;
//    @Override
//    public List<Map> getActive() {
////        List<Map> active = mapper.getActive();
////        return active;
//        return null;
//    }
//
//}
@Service
public class GroupOnServiceImpl implements GroupOnService {
    @Autowired
    private GroupOnMapper mapper;
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private ObjectMapperUtil objectMapperUtil;
    @Override
    public List<Map> getActive() {
        List<Map> active = mapper.getActive();
        return active;
    }

    @Override
    public Result getGroupOnGoods(Map map) {
        Integer pages =Integer.parseInt(map.get("page").toString());
        Integer size =Integer.parseInt(map.get("size").toString());

        //先从redis中获取
        String s = template.opsForValue().get(StorageVariable.GROUPONGOODS + ":" + pages);
        String s1 = template.opsForValue().get(StorageVariable.GROUPONGOODS);

        Page page= PageHelper.startPage(pages,size);
        Map mapss=new HashMap();
        if (StrUtil.isEmpty(s)||StrUtil.isEmpty(s1)){
            //为空,数据库查询
            mapper.getGroupOnGoods();
            List<Map> goods = page.getResult();

                template.opsForValue().set(StorageVariable.GROUPONGOODS + ":" + pages,objectMapperUtil.toJsonString(goods),7, TimeUnit.DAYS);
                template.opsForValue().set(StorageVariable.GROUPONGOODS,String.valueOf(page.getTotal()));
                mapss.put("goodsList",goods);
                mapss.put("count",page.getTotal());
            return Result.result(InfoCode.OK,InfoCode.MESSAGE_OK,goods,System.currentTimeMillis());
        }
        //不为空
            List<Map> maps = objectMapperUtil.fromJsonString(s, new TypeReference<List<Map>>() {
            });
            mapss.put("goodsList",maps);
            mapss.put("count",Integer.parseInt(s1));
            return Result.result(InfoCode.OK,InfoCode.MESSAGE_OK,mapss,System.currentTimeMillis());
    }
}
